import Taro from "@tarojs/taro"
import {http} from "./http"
import {
  BANNERS,
  GET_SITE_MODE,
  INDEX_DIY,
  SITE_SITEPAGE,
  TARO_ENV,
  APPLICATION_VIP_AD_IMG,
  VIP_USER, TECH_SUPPORT, GET_BD_INFO
} from "../constants/api"
import {vcGetCache, vcSetCache} from "./tools";
import {Banner, IndexDiyType} from "./server.interface";
import {user} from "./user.service";
import {newHttp} from "./request";

export async function getSiteList() {
  let siteList = vcGetCache('siteListStorage')
  if (!siteList) {
    const res = await http.HPost(SITE_SITEPAGE, {});
    siteList = res.map(item => {
      return {
        domains: item.domains,
        mpkey: item.mpkey,
        label: item.name,
        uuid: item.uuid
      }
    })
    // 分钟缓存
    vcSetCache('siteListStorage', siteList, 300)
  }
  return siteList
}

export async function getSiteMode() {
  const mode = await http.HGet(GET_SITE_MODE)
  return mode.siteMode
}

export async function getVIPUser() {
  return await newHttp.catchGet(VIP_USER, {})
}

export async function getIsMember() {
  const userInfo: any = await getVIPUser()
  return userInfo.status === 1
}

export async function fetchSupport() {
  let support = vcGetCache('support')
  if (!support) {
    support = await http.get(TECH_SUPPORT, {})
    vcSetCache('support', support, 300)
  }
  return support
}

export async function getBdInfo() {
  if (process.env.TARO_ENV !== 'tt') {
    return false
  }
  let bdInfo = vcGetCache('bdInfo')
  if (!bdInfo) {
    bdInfo = await http.carGet(GET_BD_INFO, {})
    vcSetCache('bdInfo', bdInfo, 500)
  }
  return bdInfo
}

export async function getMemberAdvertisement(params) {
  if (!process.env.IS_SHOW_MEMBER) {
    return ''
  }
  // 未登录 或者 是会员不显示广告位
  if (!await user.checkLogin()) {
    return ''
  }
  if (await getIsMember()) {
    return ''
  }
  const data = await http.carGet(APPLICATION_VIP_AD_IMG, params)
  return data.application_vip_ad_img || ''
}

export async function getBanner(params) {
  return await http.get<Banner[]>(BANNERS, params) || []
}

export async function getIndexDiy(params) {
  return await http.get<IndexDiyType>(INDEX_DIY, params)
}

export function getMenuButtonBoundingClientRect() {
  return (TARO_ENV === 'h5' || TARO_ENV === 'tt') ? {} : Taro.getMenuButtonBoundingClientRect()
}
